package com.yhy.common.rabbitmq.callback;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.Optional;

/**
 * 消息到达broker确认
 */
@Slf4j
public abstract class ConfirmCallback implements RabbitTemplate.ConfirmCallback {

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String dataId = Optional.ofNullable(correlationData).orElse(new CorrelationData()).getId();
        if (ack) {
            log.debug("succeeded to published message to broker! id: {}", dataId);
            enhance(correlationData);
        } else {
            log.error("failed to published message to broker! id: {}, cause: {}", dataId, cause);
            compensate(correlationData, cause);
        }
    }

    protected void enhance(CorrelationData correlationData) {
        // uncheck
    }

    protected abstract void compensate(CorrelationData correlationData, String cause);

}